//
//  WHChangeBankController.m
//  SquirrelSeller
//
//  Created by 邓伟浩 on 2019/1/14.
//  Copyright © 2019 邓伟浩. All rights reserved.
//

#import "WHChangeBankController.h"
#import "WHInputInfoCell.h"
#import "WHBankNameHelper.h"

@interface WHChangeBankController ()<UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) UITableView *dataTableView;
@property (nonatomic, strong) NSArray *tipsArray;
@property (nonatomic, strong) NSArray *placeHolderArray;
@property (nonatomic, strong) NSMutableArray *useInfoArray;

@property (nonatomic, strong) UILabel *tipsLabel;

@end

@implementation WHChangeBankController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationItem.title = @"银行卡绑定";
    
    [self initParams];
    [self setUpTableView];
}

- (void)initParams {
    _tipsArray = @[@"    姓名", @"身份证", @"开户行", @"    卡号"];
    _placeHolderArray = @[@"请输入姓名", @"请输入身份证号码", @"请输入开户银行", @"请输入银行卡卡号"];
    _useInfoArray = @[userManager.bankModel.cardName?:@"数据异常", userManager.bankModel.cardNumber?:@"数据异常", @"", @""].mutableCopy;
}

- (void)setUpTableView {
    UITableView *dataTableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    [self.view addSubview:dataTableView];
    dataTableView.delegate = self;
    dataTableView.dataSource = self;
    dataTableView.tableFooterView = [self tableFootView];
    
    [dataTableView registerClass:[WHInputInfoCell class] forCellReuseIdentifier:NSStringFromClass([WHInputInfoCell class])];
    dataTableView.backgroundColor = CViewBgMainColor;
    dataTableView.separatorColor = CLineColor;
    dataTableView.separatorInset = UIEdgeInsetsMake(0, KNormalSpace, 0, -KNormalSpace);
    
    [dataTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.mas_equalTo(self.view);
        make.top.mas_equalTo(self.view.mas_top).offset(kTopHeight);
    }];
    _dataTableView = dataTableView;
}

- (UIView *)tableFootView {
    UIView *tableFootView = [[UIView alloc] init];
    tableFootView.frame = CGRectMake(0, 0, KScreenWidth, kRealwidth(115));
    
    UILabel *tipsLabel = [[UILabel alloc] init];
    [tableFootView addSubview:tipsLabel];
    tipsLabel.textColor = CMDarkOrangeColor;
    tipsLabel.font = SYSTEMFONT(kRealwidth(15));
    tipsLabel.textAlignment = NSTextAlignmentRight;
    tipsLabel.frame = CGRectMake(kRealwidth(15), kRealwidth(15), KScreenWidth-2*kRealwidth(15), kRealwidth(15));
    _tipsLabel = tipsLabel;
    
    UIButton *submitButton = [UIButton buttonWithType:UIButtonTypeCustom];
    submitButton.frame = CGRectMake(kRealwidth(32), kRealwidth(50), KScreenWidth-2*kRealwidth(32), kRealwidth(45));
    ViewRadius(submitButton, kRealwidth(45)/2);
    [tableFootView addSubview:submitButton];
    NSString *logoutTitle = @"绑定";
    NSAttributedString *attributeStr = [[NSAttributedString alloc] initWithString:logoutTitle attributes:@{NSFontAttributeName:SYSTEMFONT(kRealwidth(17)), NSForegroundColorAttributeName:KWhiteColor}];
    [submitButton setAttributedTitle:attributeStr forState:UIControlStateNormal];
    submitButton.backgroundColor = CMDarkOrangeColor;
    [submitButton addTarget:self action:@selector(submit:) forControlEvents:UIControlEventTouchUpInside];
    
    return tableFootView;
}

#pragma mark - —————— UITableViewDelegate & UITableViewDataSource ——————

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _placeHolderArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    WHInputInfoCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([WHInputInfoCell class]) forIndexPath:indexPath];
    cell.tipsLabel.text = _tipsArray[indexPath.row];
    cell.messageField.text = _useInfoArray[indexPath.row];
    [cell setInputTextPlaceHolder:_placeHolderArray[indexPath.row]];
    
    kWeakSelf(self);
    cell.textChangeBlock = ^(NSString *text) {
        [weakself.useInfoArray replaceObjectAtIndex:indexPath.row withObject:text];
        if (indexPath.row == 3) {
            if(text.length>=16 && text.length<=19) {
                NSString *totalName = [WHBankNameHelper returnBankName:text];
                weakself.tipsLabel.text = totalName;
                weakself.tipsLabel.textColor = CMDarkOrangeColor;
            } else {
                weakself.tipsLabel.text = @"等待识别...";
                weakself.tipsLabel.textColor = CFontContentGrayColor;
            }
            
        }
    };
    
    if (indexPath.row == 2) {
        cell.validType = ValideTypeUnkonw;
        cell.messageField.enabled = YES;
    } else if (indexPath.row == 3) {
        cell.validType = ValideTypeBankCard;
        cell.messageField.enabled = YES;
    } else {
        cell.messageField.enabled = NO;
    }
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return kRealwidth(55);
}

#pragma mark - —————— 事件 ——————

- (void)submit:(UIButton *)button {
    [self.view endEditing:YES];
    NSString *openBank = _useInfoArray[2];
    NSString *cardNum = _useInfoArray[3];
    
    if (openBank.length == 0) {
        [WHView showHudMsg:@"请输入开户银行"];
        return;
    }
    if(cardNum.length<16 || cardNum.length>19) {
        [WHView showHudMsg:@"卡号不合法,请重新输入"];
        return;
    }
    if ([_tipsLabel.text containsString:@"信用卡"]) {
        [WHView showAlertwithTitle:nil message:@"不可绑定信用卡"];
        return;
    }
    
    [self updateBankCard];
}

#pragma mark - —————— 接口 ——————

- (void)updateBankCard {
    NSString *postURL = NSStringFormat(@"%@%@", URL_main, URL_updateBankCard);
    NSString *bankName = [WHBankNameHelper returnBankName:_useInfoArray[3]];
    
    NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
                          @(userManager.detailUserInfo.userId), @"userId",
                          bankName, @"bankName",
                          _useInfoArray[2], @"openingBank",
                          _useInfoArray[3], @"bankNumber",
                          nil];
    
    [WHNetworkManager requestWithURL:postURL parameters:dict isUpData:YES Success:^(id responseObject) {
        DLog(@"%@", responseObject);
        if (ValidDict(responseObject)) {
            NSNumber *code = responseObject[@"errcode"];
            NSString *errorMsg = responseObject[@"errmsg"];
            if (code.intValue == 0) {
                [WHView showAlertwithTitle:nil message:@"绑定成功"];
                NSDictionary *retDict = responseObject[@"retobj"];
                userManager.bankModel = [WHBankModel modelWithDictionary:retDict];
                [self.navigationController popViewControllerAnimated:YES];
                
            } else {
                [WHView showHudMsg:errorMsg];
            }
        }
    } failure:^(NSError *error) {
        
    }];
}

@end
